<template>
  <div>
    <div class="top0">
      <el-image style="width: 80px;margin-left:24px" class="fl" :src="require('@/assets/image/logo.png')" fit="fill"></el-image>

      <div class="top-title fl">岗位能力考核系统</div>
    </div>
    <div class="main">
      <div style="width:100%;height:24px"></div>
      <div v-for="(item, index) in table" :key="index" :class="(index%2==0?' fl':' fr')+(item.statusId!=2?' card1':' card2')">
        <div class="card-title">{{item.name}}<span style="font-size:12px;color:red" v-if="item.video==1">(需要拍照)</span><span style="font-size:12px" v-else>(无需拍照)</span></div>
        <div class="card-text">开始时间：{{item.computerStartDatetime}}</div>
        <div class="card-text">结束时间：{{item.computerEndDatetime}}</div>
        <div class="card-text">总分：{{item.totalScore}}</div>
        <!-- <div class="card-text">考场：{{item.name}}</div> -->
        <div class="card-bottom">
          <div>地点：{{item.computerPlace}}</div>
          <div class="button shou" v-if="item.statusId==2&&item.examineeScore.examineeStatusId==1&&item.video==1" @click="index_kaoshi=index;dialog=true;callCamera()">
            开始考试<i class="el-icon-arrow-right" style="font-size:18px;font-weight:bold"></i>
          </div>
          <div class="button shou" v-if="item.statusId==2&&item.examineeScore.examineeStatusId==1&&item.video!=1" @click="ready(item)">
            开始考试<i class="el-icon-arrow-right" style="font-size:18px;font-weight:bold"></i>
          </div>
          <div class="button shou" v-if="item.statusId==2&&item.examineeScore.examineeStatusId==2&&item.video==1" @click="index_kaoshi=index;dialog=true;callCamera()">
            继续考试<i class="el-icon-arrow-right" style="font-size:18px;font-weight:bold"></i>
          </div>
          <div class="button shou" v-if="item.statusId==2&&item.examineeScore.examineeStatusId==2&&item.video!=1" @click="ready(item)">
            继续考试<i class="el-icon-arrow-right" style="font-size:18px;font-weight:bold"></i>
          </div>
          <div class="button1" v-if="item.examineeScore.examineeStatusId==3">
            已交卷
          </div>
          <div class="button1" v-if="item.examineeScore.examineeStatusId==4">
            缺考
          </div>
          <div class="button1" v-if="item.statusId==1">
            未开考
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="拍照确认" width="50%" :visible.sync="dialog">
      <div class="dialog-body">
        <!--图片展示-->
        <video class="fl" ref="video" width="280" height="210" autoplay></video>
        <div slot="footer" class="dialog-footer" style="height:50px;line-height:50px">
          <el-button v-if="panduan" size="mini" @click="photograph()">拍照</el-button>
          <h4 v-else>请检查拍照的硬件设备（摄像头）</h4>
        </div>
        <!--canvas截取流-->
        <canvas v-show="!imgSrc" class="fl" ref="canvas" :width="width" :height="height"></canvas>
        <img v-show="imgSrc" :src="imgSrc" alt class="tx_img" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="toReady()">开始考试</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import $http from '@/utils/request'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data () {
    return {
      panduan: false,
      // 宽高比例四比三
      width: 280,
      height: 210,
      imgSrc: '',
      span1: 3,
      span2: 9,
      dialog: false,
      index_kaoshi: 0,
      index_jibie: 0,
      value: '',
      values: [],
      table: [],
      jibies: [{
        name: '级别一',
        value: 1,
      }, {
        name: '级别二',
        value: 2,
      }],
      zhuanyes: [{
        panduan: false
      },{
        panduan: false
      }],
      form: {
        account: '',
        createDatetime: '',
        id: '',
        idcard: '',
        logicalDelete: false,
        name: '',
        password: '',
        phone: '',
        portrait: '',
        professionId: '',
        sex: '',
        statusId: ''
      }
    }
  },
  mounted () {
    this.form = JSON.parse(localStorage.getItem('info'))
    $http.get('/examinee/exam/query/examlist/' + this.form.id).then(response => {
        if (response.success) {
          this.table = response.data
        } else  {
          this.$message({
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
        
      }).catch(error => {
        console.log(error)
      })
  },
  methods: {
    ready(item) {
      $http.post('/examinee/exam/add/begainimage', this.qs.stringify({
          begainImage: '',
          examId: item.id,
          examineeId: this.form.id
        })).then(response => {
          if (response.success) {
            localStorage.setItem('shijuan', JSON.stringify(item))
            localStorage.removeItem('answer') // 清除试卷答案缓存
            this.$router.push({
                path:"/ready",//目标路径
                query:{
                    id: item.paperId,//要传的值
                }
            })
          } else  {
            this.$message({
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
          
        }).catch(error => {
          console.log(error)
        })
    },
    toReady() {
      if (this.imgSrc === '') {
        this.$message.success('拍照后才可以开始考试')
      }
      let fileData = this.base64ToFile(this.imgSrc)
      let form = new FormData()
      // form.append('bizType', 9)
      let fileOfBlob = new File([fileData], new Date()+'.jpg')
      form.append('file',fileOfBlob)
      $http.post('/file/upload/begainimage', form).then(res => {
        if (res.success) {
          $http.post('/examinee/exam/add/begainimage', this.qs.stringify({
            begainImage: res.data,
            examId: this.table[this.index_kaoshi].id,
            examineeId: this.form.id
          })).then(response => {
            if (response.success) {
              this.dialog = false
              this.closeCamera()
              localStorage.setItem('shijuan', JSON.stringify(this.table[this.index_kaoshi]))
              localStorage.removeItem('answer') // 清除试卷答案缓存
              this.$router.push({
                  path:"/ready",//目标路径
                  query:{
                      id: this.table[this.index_kaoshi].paperId,//要传的值
                  }
              })
            } else  {
              this.$message({
                message: response.msg,
                type: 'error',
                duration: 2000
              })
            }
            
          }).catch(error => {
            console.log(error)
          })
        } else  {
          this.$message({
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
        
      }).catch(error => {
        console.log(error)
      })
    },

    // 调用摄像头
    callCamera () {
      this.panduan = true
      // H5调用电脑摄像头API
      navigator.mediaDevices.getUserMedia({
        video: true
      }).then(success => {
        // 摄像头开启成功
        this.$refs['video'].srcObject = success
        // 实时拍照效果
        this.$refs['video'].play()
        this.panduan = true
      }).catch(error => {
        this.panduan = true
        console.error('摄像头开启失败，请检查摄像头是否可用！')
        this.$message.error('摄像头开启失败，请检查摄像头是否可用！')
      })
    },
    //base64格式数据转换为file类型的文件
    base64ToFile(urlData, fileName) {
    let arr = urlData.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let bytes = atob(arr[1]); // 解码base64
    let n = bytes.length
    let ia = new Uint8Array(n);
    while (n--) {
        ia[n] = bytes.charCodeAt(n);
    }
    return new File([ia], fileName||'image/jpeg', { type: mime });
},
    // 拍照
    photograph () {
      let ctx = this.$refs['canvas'].getContext('2d')
      // 把当前视频帧内容渲染到canvas上
      ctx.drawImage(this.$refs['video'], 0, 0, this.width, this.height)
      // 转base64格式、图片格式转换、图片质量压缩
      let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7)

      // var image = imgBase64.toDataURL("image/png");
      this.imgSrc = imgBase64;//赋值并预览图片
      
　　　 // 由字节转换为KB 判断大小
      let str = imgBase64.replace('data:image/jpeg;base64,', '')
      let strLength = str.length
      let fileLength = parseInt(strLength - (strLength / 8) * 2)
　　　 // 图片尺寸  用于判断
      let size = (fileLength / 1024).toFixed(2)
      console.log(size)

      // this.closeCamera()

 　　  // 上传拍照信息  调用接口上传图片 .........

      // 保存到本地
      // let ADOM = document.createElement('a')
      // ADOM.href = this.headImgSrc
      // ADOM.download = new Date().getTime() + '.jpeg'
      // ADOM.click()
    },
    // 关闭摄像头
    closeCamera () {
      if (!this.$refs['video'].srcObject) return
      let stream = this.$refs['video'].srcObject
      let tracks = stream.getTracks()
      tracks.forEach(track => {
        track.stop()
      })
      this.$refs['video'].srcObject = null
    },
  }
}
</script>

<style lang="scss" scoped>
.top-jibie{
  float: left;
  width: 60px;
  height: 46px;
  margin-right: 30px;
  color: rgba(153, 153, 153, 100);
  font-size: 14px;
  text-align: center;
  font-family: PingFangSC-Regular;
  display: flex;
  justify-content: center;
  align-items: center;
}
.top-select {
  color: #1890FF;
  border-bottom: 2px solid #1890FF;
}
.top-right{
  float: right;
  width: 100px;
  height: 36px;
  color: rgba(255, 255, 255, 100);
  font-size: 16px;
  text-align: left;
  font-family: MicrosoftYaHei-Bold;
  border-radius: 4px;
  background-color: rgba(24, 144, 255, 1);
  display: flex;
  justify-content: center;
  align-items: center;
}
.add{
  width:100%;
  height: 41px;
  margin: 24px 0 20px 0;

  color: rgba(24, 144, 255, 100);
  font-size: 16px;
  font-family: MicrosoftYaHei;

  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid rgba(24, 144, 255, 1);
  border-radius: 4px;
}
.icon-color1{
  color: #C2C3C4;
}
.icon-color2{
  color: rgba(51, 51, 51, 1);
}
.label{
  line-height:30px;
  float: right;
}
.el-col{
  margin-bottom:10px;
}
.top-title{
    color: rgba(102, 102, 102, 100);
    font-size: 20px;
    font-family: MicrosoftYaHei;
    font-weight: bold;
    margin-left: 12px;
}
.card{
  width: 100%;
  overflow: hidden;
}
.card1{
  width: calc(50% - 14px);
  height: 180px;
  overflow: hidden;
  margin-bottom: 28px;
  padding: 24px 26px 15px 30px;
  background-color: rgba(255, 255, 255, 1);
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.09);
  border: 1px solid rgb(167, 161, 161);
  color: #999999;
  font-size: 14px;
  font-family: MicrosoftYaHei;
  .card-title{
    color: #666666!important;
  }
}
.card2{
  width: calc(50% - 14px);
  height: 180px;
  overflow: hidden;
  margin-bottom: 28px;
  padding: 24px 26px 15px 30px;
  background-color: rgba(227, 237, 255, 1);
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.09);
  border: 1px solid rgba(30, 144, 251, 1);
  color: #666666;
  font-size: 14px;
  font-family: MicrosoftYaHei;
}
.card-title{
  color: rgba(51, 51, 51, 100);
  font-size: 18px;
  font-family: MicrosoftYaHei;
  font-weight: bold;
  margin-bottom: 10px;
}
.card-text{
  margin-top: 6px;
}
.card-bottom{
  width:100%;
  min-height:32px;
  margin-top:6px;
  display:flex;
  justify-content:space-between;
  // align-items:center;
}
.button{
  margin-top: -3px;
  min-width:93px;
  height: 26px;
  padding-left: 3px;
  font-size: 18px;
  font-weight: bold;
  font-family: MicrosoftYaHei;
  color: #1E90FB;
  border-bottom: 2px solid #1E90FB;
}
.button1{
  margin-top: -3px;
  min-width:100px;
  color: #999999;
  font-size: 18px;
  font-weight: bold;
  font-family: MicrosoftYaHei;
}
.top0{
  widows: 100%;
  height: 94px;
  display: flex;
  // justify-content:center;
  align-items:center;
  background-color: white;
}
.dialog-body{
  overflow: hidden;
  margin: 0 auto;
  width: 600px;
  min-height:400px;
  display: flex;
  flex-direction:column;
  justify-content: center;
  align-items:center;
}
</style>
